var fs = require('fs')
var express = require('express')
var bodyParser = require('body-parser')
var router = express.Router() // express 封装的路由 API
var studb = require('./student-db')


router.get('/students',(req,res)=>{
    studb.find().then(data=>{
        res.render('index.html',{
            students: data
        })
    })
})

router.get('/students/add',(req,res)=>{
    res.render('add.html')
})

router.post('/students/add',(req,res)=>{
    studb.find().then(data=>{
        req.body.id = data.length
    })
    new studb(req.body).save()
    res.redirect('/students')
})

router.get('/students/edit',(req,res)=>{
    var id = req.query.id.replace(/"/g,'')
    studb.findById(id).then(data=>{
        res.render("edit.html",{
            id:id,
            name:data.name,
            age:data.age,
            gender:data.age,
            hobby:data.hobby
        })
    },err=>{
        console.log(err.message)
    })
})

router.post('/students/edit',(req,res)=>{
    studb.findByIdAndUpdate(req.body.id,{
        name: req.body.name,
        gender: Number(req.body.gender),
        age: Number(req.body.age),
        hobby: req.body.hobby
    }).then(data=>{
        console.log("修改成功")
        res.redirect('/students')
    },err=>{
        console.log(err.message)
    })
    
})

router.get('/students/delete',(req,res)=>{
    var id = req.query.id.replace(/"/g,'')

    studb.findByIdAndRemove(id).then(data=>{
        console.log('删除成功')
        res.redirect('/students')
    },err=>{
        console.log(err.message)
    })
})

module.exports = router